﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Timers;
using AllInOne.Models;
using AllInOne.Entity;
using PropertyChanged;
using AllInOne.HDI.CRT_591_M001;
using System.Text.RegularExpressions;
using AllInOne.ModelDb;
using AllInOne.Classes;
using AllInOne.Pages;

namespace AllInOne.MainPages
{
    /// <summary>
    /// 获取发卡信息页面
    /// </summary>
    [AddINotifyPropertyChangedInterface]
    public partial class GiveCard_Page : Page
    {
        private MainWindow parent;

        private Timer tipsTimer;

        private UInt32 Hdle = 0;

        public GiveCard_Page()
        {
            InitializeComponent();
        }

        public GiveCard_Page(MainWindow parent)
        {
            InitializeComponent();
            this.parent = parent;
            this.InitTimer();
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //01 初始化信息
            InitLoadData();
            //02 发卡机句柄
            this.Hdle = this.parent.Hdle;
            //03 查询限制拉货数据
            //nitVerifyPlateData();
        }

        #region 初始化
        List<string> productListStr = new List<string>();
        List<Company> CompanyList = new List<Company>();
        List<CustomBaseData> CustomerTypeList = new List<CustomBaseData>();

        List<string> senderListStr = new List<string>();
        List<string> receiverListStr = new List<string>();
        List<ProductList> productList;
        List<SenderList> senderList;
        List<ReceiverList> receiverList;

        List<BlackList> blackList;
        private bool InitLoadData()
        {
            try
            {
                //先清理
                ac_cb_product.ClearItem();
                ac_cb_sender.ClearItem();
                ac_cb_receiver.ClearItem();
                Dispatcher.Invoke(new Action(() =>
                {
                    tb_InputPlate.Text = "XXXXXXX";
                }));
                //加载三大基础信息
                productList = ServiceWebApi.GetProductList();
                if (productList != null)
                {
                    #region 初始货物信息
                    productListStr.Add("多种货物");
                    ac_cb_product.AddItem(new AutoCompleteEntry("多种货物", null));
                    for (int i = 0; i < productList.Count(); i++)
                    {
                        productListStr.Add(productList[i].product);
                        ac_cb_product.AddItem(new AutoCompleteEntry(productList[i].product, null));
                    }
                    //cb_product.ItemsSource = productListStr;
                    #endregion
                }
                
                senderList = ServiceWebApi.GetSenderList();
                if (senderList != null)
                {
                    for (int i = 0; i < senderList.Count; i++)
                    {
                        if (SystemParam.ShowSelect)
                        {
                            if (senderList[i].inputcode == SystemParam.InputCode)
                            {
                                senderListStr.Add(senderList[i].sender);
                                ac_cb_sender.AddItem(new AutoCompleteEntry(senderList[i].sender, null));
                            }
                        }
                        else
                        {
                            senderListStr.Add(senderList[i].sender);
                            ac_cb_sender.AddItem(new AutoCompleteEntry(senderList[i].sender, null));
                        }
                    }
                }
                if (senderListStr != null)
                {
                    #region 初始化发货单位信息
                    //for (int i = 0; i < senderList.Count(); i++)
                    //{
                    //    senderListStr.Add(senderList[i].sender);
                    //}
                    //cb_sender.ItemsSource = senderListStr;
                    #endregion
                }
                receiverList = ServiceWebApi.GetReceiverList();
                if (receiverList != null)
                {
                    #region 初始化收货单位信息
                    for (int i = 0; i < receiverList.Count(); i++)
                    {
                        receiverListStr.Add(receiverList[i].receiver);
                        ac_cb_receiver.AddItem(new AutoCompleteEntry(receiverList[i].receiver, null));
                    }

                    //cb_receiver.ItemsSource = receiverListStr;
                    #endregion
                }
                ////发货单位对应的客户类型
                //CustomerTypeList = ServiceWebApi.GetCustomerTypeList();

                ////查询黑名单
                //blackList = ServiceWebApi.
                SimpleConsole.WriteInfo("入厂制卡-信息录入-加载基础信息-完成", this);
                return true;
            }
            catch (Exception ex)
            {
                SimpleConsole.WriteInfo("入厂制卡-信息录入-加载基础信息-异常" + ex.ToString(), this);
                return false;
            }
        }

        /// <summary>
        /// 初始化验证车牌数据加载
        /// </summary>
        /// <returns></returns>
        private bool InitVerifyPlateData()
        {
            try
            {
                //先清理
                ac_cb_product.ClearItem();
                ac_cb_sender.ClearItem();
                ac_cb_receiver.ClearItem();

                productListStr.Add("多种货物");
                ac_cb_product.AddItem(new AutoCompleteEntry("多种货物", null));
                //加载三大基础信息
                productList = ServiceWebApi.GetProductList();
                if (productList != null)
                {
                    #region 初始货物信息
                    for (int i = 0; i < productList.Count(); i++)
                    {
                        productListStr.Add(productList[i].product);
                        ac_cb_product.AddItem(new AutoCompleteEntry(productList[i].product, null));
                    }
                    //cb_product.ItemsSource = productListStr;
                    #endregion
                }
                CompanyList = ServiceWebApi.GetCompany();
                if (CompanyList != null)
                {
                    for (int i = 0; i < CompanyList.Count; i++)
                    {
                        senderListStr.Add(CompanyList[i].Name);
                        ac_cb_sender.AddItem(new AutoCompleteEntry(CompanyList[i].Name, null));
                    }
                }
                if (senderListStr != null)
                {
                    #region 初始化发货单位信息
                    //for (int i = 0; i < senderList.Count(); i++)
                    //{
                    //    senderListStr.Add(senderList[i].sender);
                    //}
                    //cb_sender.ItemsSource = senderListStr;
                    #endregion
                }
                receiverList = ServiceWebApi.GetReceiverList();
                if (receiverList != null)
                {
                    #region 初始化收货单位信息
                    for (int i = 0; i < receiverList.Count(); i++)
                    {
                        receiverListStr.Add(receiverList[i].receiver);
                        ac_cb_receiver.AddItem(new AutoCompleteEntry(receiverList[i].receiver, null));
                    }

                    //cb_receiver.ItemsSource = receiverListStr;
                    #endregion
                }
                SimpleConsole.WriteInfo("入厂制卡-信息录入-加载基础信息-完成", this);
                return true;
            }
            catch (Exception ex)
            {
                SimpleConsole.WriteInfo("入厂制卡-信息录入-加载基础信息-异常" + ex.ToString(), this);
                return false;
            }
        }

        /// <summary>
        /// 得到身份证信息
        /// </summary>
        public void InitPage()
        {
            try
            {
                //把姓名赋值上去
                tb_DriverName.Text = this.parent.DriverInfo.xm;
                //先清理 其他的信息都为空--此为多次进入时要处理的
                InitPageShow(this.parent.DriverInfo.xm);
            }
            catch (Exception)
            {
            }
            //this.imgTitle.Source = new BitmapImage(new Uri(this.parent.enterBusinessInfo.getImgTitleUrl()));
        }



        #endregion

        #region 扫码制卡--初始化

        /// <summary>
        /// 扫码制卡初始化
        /// </summary>
        public void QRCode_InitPage(QRCodeInfoModel model)
        {
            if (this.parent.DriverInfo == null)
            {
                this.parent.DriverInfo = new DriverInfo();
            }
            this.parent.DriverInfo.xm = model.RegName;
            this.parent.DriverInfo.sfzmhm = model.IdentityNum;//身份证号
            this.parent.DriverInfo.zz = "";
            //把相应的赋值上去
            tb_DriverName.Text = model.RegName;
            btn_Phone.Content = model.RegPhone;
            ac_cb_sender.Text = model.Company;
            ac_cb_receiver.Text = model.Receiver;
            ac_cb_product.Text = model.GoodsName;
            tb_InputPlate.Text = model.Plate;
            btn_Sender_Tare.Content = model.SenderTare;
            btn_Sender_Gross.Content = model.SenderGross;
            btn_Sender_Net.Content = model.SenderNet;
            tb_DriverName2.Text = model.DriverName2;
            btn_Phone2.Content = model.DriverPhone2;
            btn_Count.Content = model.iCount;
            //客户类型--先不进行处理--与当前数据保持量致
        }
        #endregion

        private void BtnBackToIndex_MouseUp(object sender, MouseButtonEventArgs e)
        {
            this.parent.ResetIndex();
        }

        private int photoIndex = 0;
        private int interval = 2;
        private int stay = 5;

        public void InitTimer()
        {
            this.tipsTimer = new Timer();
            this.tipsTimer.Interval = 100;
            this.tipsTimer.Elapsed += new ElapsedEventHandler(delegate (object sender, ElapsedEventArgs e)
            {

                photoIndex++;
                int step = 1;
                if (photoIndex > 0 && photoIndex < 4 * interval)
                {
                    step = photoIndex / interval + 1;
                }
                else
                {
                    step = 5;
                    if (photoIndex > stay + 4 * interval)
                    {
                        photoIndex = 0;
                    }
                }
            });
            this.tipsTimer.Enabled = false;
        }
        private void BtnConfirm_MouseUp(object sender, MouseButtonEventArgs e)
        {
            //01先判断是不是车牌号
            if (tb_InputPlate.Text == "" || tb_InputPlate.Text == "XXXXXXX")
            {
                MessageBox.Show("车牌号位数不对,不能提交！");
                return;
            }
            //日期：2022年9月2日--还未做
            //铁粉或者其他货物，只有当天才知道哪些车辆可以拉这些货物

            #region 获取数据并去掉可能有的换行符
            string ICardNum = "";
            string RegName = this.parent.DriverInfo.xm;
            string IdentityNum = this.parent.DriverInfo.sfzmhm;
            string Address = this.parent.DriverInfo.zz;//住址

            int OpType = 1;//1自助机制卡, 2表示手动制卡
            string Company = ac_cb_sender.Text;
            string Receiver = ac_cb_receiver.Text;
            string GoodsName = ac_cb_product.Text;
            string Plate = tb_InputPlate.Text;

            string RegPhone = btn_Phone.Content.ToString();
            string SenderTare = btn_Sender_Tare.Content.ToString();
            string SenderGross = btn_Sender_Gross.Content.ToString();
            string SenderNet = btn_Sender_Net.Content.ToString();
            string DriverName2 = tb_DriverName2.Text;
            string DriverPhone2 = btn_Phone2.Content.ToString();
            string PiCi = btn_PiCi.Content.ToString();
            if (PiCi == "" || PiCi == "0")
            {
                PiCi = "无";
            }

            //去掉换行符
            Company = Regex.Replace(Company, @"[/n/r]", "");
            Receiver = Regex.Replace(Receiver, @"[/n/r]", "");
            GoodsName = Regex.Replace(GoodsName, @"[/n/r]", "");
            Plate = Regex.Replace(Plate, @"[/n/r]", "");
            RegPhone = Regex.Replace(RegPhone, @"[/n/r]", "");
            SenderTare = Regex.Replace(SenderTare, @"[/n/r]", "");
            SenderGross = Regex.Replace(SenderGross, @"[/n/r]", "");
            SenderNet = Regex.Replace(SenderNet, @"[/n/r]", "");
            DriverName2 = Regex.Replace(DriverName2, @"[/n/r]", "");
            DriverPhone2 = Regex.Replace(DriverPhone2, @"[/n/r]", "");

            int iCount = 0;
            try
            {
                if (string.IsNullOrEmpty(btn_Count.Content.ToString()))
                {
                    iCount = 0;
                }
                else
                {
                    string txtCountStr = btn_Count.Content.ToString();
                    txtCountStr = Regex.Replace(txtCountStr, @"[/n/r]", "");
                    iCount = Convert.ToInt32(txtCountStr);
                }
                
            }
            catch (Exception ex)
            {
                iCount = 0;
                SimpleConsole.WriteInfo("发卡机-件数 " + ex.ToString(), this);
            }

            int iSenderTare = 0;
            int iSenderGross = 0;
            int iSenderNet = 0;
            try
            {
                iSenderTare = Convert.ToInt32(SenderTare);
            }
            catch { }
            try
            {
                iSenderGross = Convert.ToInt32(SenderGross);
            }
            catch { }
            try
            {
                iSenderNet = Convert.ToInt32(SenderNet);
            }
            catch { }
            #endregion

            T_RegisterInfo obj = new T_RegisterInfo();
            obj.Revicer = Receiver;
            obj.RegPhone = RegPhone;

            obj.ICardNum = ICardNum;
            obj.RegName = RegName;
            obj.IdentityNum = IdentityNum;
            obj.OpType = OpType;
            obj.Company = Company;
            //2023年1月7日08:46:53 去掉收货单位的id 因为存在一对多的问题
            //obj.CompanyId = ReturnCompanyId(Company);
            obj.CompanyId = 0;//不进行维护
            obj.Position = Receiver;
            obj.GoodsName = GoodsName;
            obj.CardStatus = 0;//此个状态最开始设置成0,并且序列号字段有值，修改完之后将序列号字段修改为加上发卡时间的形式
            obj.Plate = Plate;
            obj.ReceiveTime = System.DateTime.Now;//此字段是为了不传空，将来保存时不会保存

            obj.SenderTare = iSenderTare;
            obj.SenderGross = iSenderGross;
            obj.SenderNet = iSenderNet;
            //件数
            obj.iCount = iCount;
            obj.CardType = this.parent.DriverInfo.cardType;//卡类型

            obj.RegPhone = RegPhone;
            obj.DriverName2 = DriverName2;
            obj.DriverPhone2 = DriverPhone2;
            obj.Guid = System.Guid.NewGuid().ToString();
            obj.Value1 = ReturnCustomerType(Company);
            obj.Value2 = "0";
            obj.Value3 = Address;
            obj.Value4 = PiCi;

            string verifyStr = "";
            //01 验证信息是否全
            if (!CheckInputData(out verifyStr))
            {
                MessageBox.Show("信息不完整不能提交：" + verifyStr);
                return;
            }

            //02 硫酸的数据--进行校验--根据备案号信息
            if (GoodsName.Contains("硫酸") && GoodsName.Contains("%"))
            {
                //2023年6月30日
                //ac_cb_product_LostFocus(null, null);
                //return;

                MessageBox.Show("硫酸货物请在出厂货物列表制卡！");
                return;
                ////1. 需要做一层验证，就是此车号在不在此备案信息下面，如果是硫酸的话。
                //string strYNumber = tb_PutOnRecordNum.Text;
                //if (string.IsNullOrEmpty(strYNumber) ||strYNumber == "XXXXXXXXXXXXXXXX")
                //{
                //    MessageBox.Show("由于是硫酸货物，故必须选填入备案号信息，以验证是否具有位货权限！");
                //    return;
                //}
                ////string strYNumber = "Y15220022878183";
                //string msg1 = "";
                ////检查这个车牌的车能否拉这些数据，
                //if (!ServiceWebApi.CheckSulphuricAcid(Plate, strYNumber,out msg1))
                //{
                //    MessageBox.Show("信息有误" + msg1);
                //    return;//不让继续
                //}
                //obj.YNumber = strYNumber;
            }

            //02-2 铁粉或者其他的货物--根据配置的当天可拉货物列表进行判断
            if (GoodsName == "铁粉")
            {
                //2-2.1. 需要做一层验证，就是此车号在不在当天的维护车号列表中
                string msgTieFen = "";
                if (!ServiceWebApi.VerifyPlate(System.DateTime.Now.ToString("yyyy-MM-dd"), GoodsName, Plate, out msgTieFen))
                {
                    MessageBox.Show("请联系工作人员：" + msgTieFen);
                    return;//必须跳出去
                }
            }

            //03 IC卡信息，这个是两步的操作，如何写成一个操作，肯定是数据录入成功了，然后进行发卡，但是
            //提示信息如何展示

            //string ICardNum, string RegName, string IdentityNum, string OpType, string Company, string Position, string GoodName, string Plate
            //02 数据保存到数据库 AddRegisterInfo

            //存身份证号加密码存储---
            if (ServiceWebApi.AddRegisterInfo(obj))
            {
                MessageBox.Show("数据保存--成功");
            }
            else
            {
                MessageBox.Show("数据保存--失败");
            }

            #region IC卡-发卡-相关操作
            //连接发卡机
            this.parent.ShowText("开始发卡");
            //this.parent.ShowTipText(string MsgType, string tip_Title, string tip_Content);
            this.parent.ShowTipText("入厂制卡", "", "");

            string strState = "";
            string UID = "";
            string msg;

            if (Hdle == 0)//说明初始化时的连接失败
            {
                string CardDispenser_PORTNAME = Classes.SystemParam.SendSerialPortName;
                int CardDispenser_BAUDRATE = Classes.SystemParam.SendBaudRate;
                Hdle = GrantCardClient.CommOpenWithBaut(CardDispenser_PORTNAME, (uint)Convert.ToUInt32(CardDispenser_BAUDRATE));
                if (Hdle == 0)
                {
                    //再次进行连接操作
                    MessageBox.Show("发卡机连接失败,请检查发卡机连接。");
                    return;
                }
                else
                {
                    if (GrantCardClient.InitCard(Hdle, "00", out msg))
                    {
                        //根据初始化结果来进行下一步的操作：
                        int index_1 = msg.IndexOf(":");
                        if (index_1 < 0)
                        {
                            MessageBox.Show("自助机返回数据格式有误");
                        }
                        string st0 = msg.Substring(index_1 + 1, 1);
                        string st1 = msg.Substring(index_1 + 2, 1);
                        string st2 = msg.Substring(index_1 + 3, 1);
                        //卡机通道
                        if (st0 == "1" || st0 == "2")
                        {
                            string msg2 = "";
                            //移进来直接放到卡槽内
                            if (GrantCardClient.MoveCardToRecycleBin(Hdle, "00", out msg2))
                            {
                                int index_02 = msg.IndexOf(":");
                                if (index_1 >= 0)
                                {
                                    string st0_2 = msg2.Substring(index_02 + 1, 1);
                                    string st1_2 = msg2.Substring(index_02 + 2, 1);
                                    string st2_2 = msg2.Substring(index_02 + 3, 1);
                                    if (st2_2 == "1")
                                    {
                                        VoiceHelper.Speak("回收箱卡满,请处联系工作人员处理。");
                                        MessageBox.Show("回收箱卡满,请处联系工作人员处理。");
                                    }
                                }
                            }
                        }
                        //发卡箱
                        if (st1 == "0")
                        {
                            VoiceHelper.Speak("卡箱无卡,请处联系工作人员处理。");
                            MessageBox.Show("卡箱无卡,请处联系工作人员处理。");
                        }
                        if (st1 == "2")
                        {
                            VoiceHelper.Speak("卡箱卡少,请处联系工作人员处理。");
                            MessageBox.Show("卡箱卡少,请处联系工作人员处理。");
                        }
                        //回收箱
                        if (st1 == "1")
                        {
                            VoiceHelper.Speak("回收箱卡满,请处联系工作人员处理。");
                            MessageBox.Show("回收箱卡满,请处联系工作人员处理。");
                        }
                        SimpleConsole.WriteInfo("发卡机-初始化成功！" + msg, this);
                    }
                    else
                    {
                        int index_1 = msg.IndexOf("错误信息:");
                        if (index_1 < 0)
                        {
                            VoiceHelper.Speak("卡机-初始化失败。" + msg);
                            MessageBox.Show("卡机-初始化失败," + msg);
                            SimpleConsole.WriteInfo("卡机-初始化失败！" + msg, this);
                        }
                        string msgInfo = msg.Substring(index_1 + 5);
                        VoiceHelper.Speak("卡机-初始化失败。");
                        MessageBox.Show("卡机-初始化失败," + msgInfo);
                        SimpleConsole.WriteInfo("卡机-初始化失败！" + msg, this);
                        return;
                    }
                }
                //如果这次连接成功，则进行赋值
                parent.Hdle = Hdle;
            }
            //记着，还要解析没有卡的情况

            //卡槽内没有卡，那么发卡肯定失败
            if (GrantCardClient.MoveCardToRF(Hdle, "00", out msg))
            {
                strState += "移卡到RF位成功;";
                //读取卡号--激活
                if (GrantCardClient.MiCardActivate(Hdle, "00", out UID, out msg))
                {
                    strState += "读取卡号成功,卡号：" + UID + ";";
                }
                else
                {
                    //失败--记录下来
                    strState += "读取卡号失败：" + msg + ";";
                }

                //下电释放--下电
                if (GrantCardClient.MiCardDactivate(Hdle, "00", out msg))
                {
                    strState += "下电释放成功;";
                }
                else
                {
                    strState += "下电释放失败;";
                }
                SimpleConsole.WriteInfo(strState, this);
            }
            else
            {
                //据据状态码进行提示错误
                this.parent.PlayVioceQueue.Enqueue("移卡到RF位失败。");
                SimpleConsole.WriteInfo("移卡到RF位失败" + msg, this);
                MessageBox.Show("移卡到RF位失败" + msg);
                return;
            }
            //UID = "123";
            //更新数据库发卡数据
            if (UID != "")
            {
                string updataMsg = "";
                obj.ICardNum = UID;
                if (ServiceWebApi.UpdataRegisterInfo(obj, out updataMsg))
                //if (ServiceWebApi.UpdataRegisterInfo(new T_RegisterInfo { ICardNum = UID, Guid = obj.Guid }, out updataMsg))
                {
                    //读取到卡号后，将卡推送到最前面。
                    if (GrantCardClient.MoveCardToFront1(Hdle, "00", out msg))
                    {
                        VoiceHelper.Speak("请取走你的卡片");
                        //MessageBox.Show("发卡成功请取走你的卡片");
                        //数据恢复到空数据装态
                        InitPageShow("");
                        this.parent.ResetIndex();
                    }
                    else
                    {
                        MessageBox.Show("移动卡片到出口失败,发卡失败！");
                    }
                }
                else
                {
                    MessageBox.Show("注册信息卡号绑定失败,发卡失败！");
                }
            }
            else
            {
                MessageBox.Show("未获取到卡号,发卡失败！");
            }
            //开始推卡到出口，还要明白发完卡，需不需要判断卡是否被取走
            //发完卡后，提供一个查询卡信息，
            #endregion
        }

        /// <summary>
        /// 数据恢复到原来状态
        /// </summary>
        /// <param name="strXingMing">测试的时候传姓名</param>
        public void InitPageShow(string strXingMing)
        {
            try
            {
                tb_DriverName.Text = string.IsNullOrEmpty(strXingMing) ? "XXX" : strXingMing;
                ac_cb_sender.Text = "";
                ac_cb_receiver.Text = "";
                ac_cb_product.Text = "";
                tb_InputPlate.Text = "XXXXXXX";
                btn_PiCi.Content = "";

                btn_Phone.Content = "";
                btn_Sender_Tare.Content = "";
                btn_Sender_Gross.Content = "";
                btn_Sender_Net.Content = "";
                tb_DriverName2.Text = "";
                btn_Phone2.Content = "";
                btn_Count.Content = "";
                //tb_Phone2.Text = "";
                //txtCount.Text = "0";//默认件数为0

                row50_Number.Visibility = Visibility.Hidden;
                row51_Number.Visibility = Visibility.Hidden;
                tb_PutOnRecordNum.Text = "";
            }
            catch { }
        }


        /// <summary>
        /// 根据发货单位名字返回Id
        /// </summary>
        /// <param name="CompanyName">发货单位名称</param>
        /// <returns></returns>
        public int ReturnCompanyId(string CompanyName)
        {
            int id = 0;
            try
            {
                var tempCompany = CompanyList.FirstOrDefault(it => it.Name == CompanyName);
                if (tempCompany != null)
                {
                    id = tempCompany.Id;
                }
            }
            catch { }
            return id;
        }

        /// <summary>
        /// 根据发货单位查询客户类型
        /// </summary>
        /// <param name="CompanyName">发货单位名称</param>
        /// <returns></returns>
        public string ReturnCustomerType(string CompanyName)
        {
            try
            {
                if (senderList != null)
                {
                    var temp = senderList.FirstOrDefault(it => it.sender == CompanyName);
                    if (temp != null && !string.IsNullOrEmpty(temp.remarktext))
                    {
                        return temp.remarktext;
                    }
                }
            }
            catch (Exception ex)
            {
                SimpleConsole.WriteInfo("查询发货单位客户类型-出错" + ex.ToString(), this);
            }
            return "";
        }

        private bool CheckInputData(out string msg)
        {
            msg = "";
            try
            {
                bool check = true;
                //if (tb_DriverName.Text == "" || tb_DriverName.Text == "XXX")
                //{
                //    msg += "司机名字为空;";
                //    check = false;
                //}
                if (tb_InputPlate.Text == "" || tb_InputPlate.Text == "XXXXXXX")
                {
                    msg += "车牌号为空;";
                    check = false;
                }
                //T_Dictionary GoodsModel = (T_Dictionary)cb_product.SelectedItem;
                //if (GoodsModel.DictItemValue == "")
                //{
                //    msg += "货物为空;";
                //    check = false;
                //}
                //string product = ac_cb_product.Text;
                //if (product == "")
                //{
                //    msg += "货物为空;";
                //    check = false;
                //}
                //后续继续添加------
                return check;
            }
            catch (Exception ex)
            {
                SimpleConsole.WriteInfo("入厂制卡-信息录入-录入基础信息验证-异常" + ex.ToString(), this);
                msg += "验证非空出错;";
                return false;
            }
        }

        private void Test_Btn1_Click(object sender, RoutedEventArgs e)
        {
            #region 自动生成 初始化信息
            //#region 初始化公司信息
            //List<Company> dl = new List<Company>();
            //for (int i = 0; i < 5; i++)
            //{
            //    Company temp = new Company();
            //    temp.guid = System.Guid.NewGuid().ToString("N");
            //    temp.code = (i + 1).ToString();
            //    temp.value = "公司" + (i + 1).ToString();
            //    dl.Add(temp);
            //}

            //cb_company.ItemsSource = dl;
            //cb_company.DisplayMemberPath = "value";
            //cb_company.SelectedValuePath = "guid";
            //#endregion

            //#region 初始化位置信息
            //List<Company> positionList = new List<Company>();
            //for (int i = 0; i < 5; i++)
            //{
            //    Company temp = new Company();
            //    temp.guid = System.Guid.NewGuid().ToString("N");
            //    temp.code = (i + 1).ToString();
            //    temp.value = "位置" + (i + 1).ToString();
            //    positionList.Add(temp);
            //}
            //cb_position.ItemsSource = positionList;
            //cb_position.DisplayMemberPath = "value";
            //cb_position.SelectedValuePath = "guid";
            //#endregion

            //#region 初始化货物信息
            //List<Company> goodsList = new List<Company>();
            //for (int i = 0; i < 50; i++)
            //{
            //    Company temp = new Company();
            //    temp.guid = System.Guid.NewGuid().ToString("N");
            //    temp.code = (i + 1).ToString();
            //    temp.value = "货物" + (i + 1).ToString();
            //    goodsList.Add(temp);
            //}
            //cb_goods.ItemsSource = goodsList;
            //cb_goods.DisplayMemberPath = "value";
            //cb_goods.SelectedValuePath = "guid";
            //#endregion
            #endregion

            if (!InitLoadData())
            {
                MessageBox.Show("基础信息加载失败");
            }
        }


        private bool InitLoadData1()
        {
            try
            {
                //List<T_Dictionary> list = ServiceWebApi.GetDicByType("Company,Position,Goods");

                //if (list != null)
                //{
                //    #region 初始化公司信息
                //    cb_company.ItemsSource = list.FindAll(p => p.ParentCode == "Company");
                //    cb_company.DisplayMemberPath = "DictItemValue";
                //    cb_company.SelectedValuePath = "Id";
                //    #endregion

                //    #region 初始化位置信息
                //    cb_position.ItemsSource = list.FindAll(p => p.ParentCode == "Position");
                //    cb_position.DisplayMemberPath = "DictItemValue";
                //    cb_position.SelectedValuePath = "Id";
                //    #endregion

                //    #region 初始化货物信息
                //    cb_goods.ItemsSource = list.FindAll(p => p.ParentCode == "Goods");
                //    cb_goods.DisplayMemberPath = "DictItemValue";
                //    cb_goods.SelectedValuePath = "Id";
                //    #endregion
                //}


                //List<T_Dictionary> list = ServiceWebApi.GetDicByType("Company,Position,Goods");

                //if (list != null)
                //{
                //    #region 初始化公司信息
                //    cb_company.ItemsSource = list.FindAll(p => p.ParentCode == "Company");
                //    cb_company.DisplayMemberPath = "DictItemValue";
                //    cb_company.SelectedValuePath = "Id";
                //    #endregion

                //    #region 初始化位置信息
                //    cb_position.ItemsSource = list.FindAll(p => p.ParentCode == "Position");
                //    cb_position.DisplayMemberPath = "DictItemValue";
                //    cb_position.SelectedValuePath = "Id";
                //    #endregion

                //    #region 初始化货物信息
                //    cb_goods.ItemsSource = list.FindAll(p => p.ParentCode == "Goods");
                //    cb_goods.DisplayMemberPath = "DictItemValue";
                //    cb_goods.SelectedValuePath = "Id";
                //    #endregion
                //}

                SimpleConsole.WriteInfo("入厂制卡-信息录入-加载基础信息-完成", this);
                return true;
            }
            catch (Exception ex)
            {
                SimpleConsole.WriteInfo("入厂制卡-信息录入-加载基础信息-异常" + ex.ToString(), this);
                return false;
            }
        }

        private void BtnInputPlate_MouseUp(object sender, MouseButtonEventArgs e)
        {
            //this.parent.ShowModifyPhone();
            //方法一：嵌入到页面里面的选择页
            //this.parent.ShowPlateInPut();

            //方法二：弹出来的页面
            ShowInputPlateWinDialog();
            //if (authModel != null)
            //{
            //    MessageBox.Show("录入车牌号信息成功:" + authModel.AuthCode);           
            //}
            //else
            //{
            //    MessageBox.Show("录入车牌号信息出错");
            //}
        }

        /// <summary>
        /// 弹出输入车牌号窗体并返回值
        /// </summary>
        /// <returns></returns>
        private void ShowInputPlateWinDialog()
        {
            string oldPlatt = "";
            if (tb_InputPlate.Text == "XXXXXXX")
            {
                oldPlatt = "";
            }
            else
            {
                oldPlatt = tb_InputPlate.Text;
            }
            //PlateInputWindow plateInputWindow = new PlateInputWindow(oldPlatt);
            PlateInputWin plateInputWindow = new PlateInputWin(oldPlatt);
            plateInputWindow.DlgDialogEvent_InputPlate -= new DlgDialog(this.DlgDialogEvent_InputPlate_AuthBack);
            plateInputWindow.DlgDialogEvent_InputPlate += new DlgDialog(this.DlgDialogEvent_InputPlate_AuthBack);
            //弹框居中
            plateInputWindow.ShowInTaskbar = false;
            plateInputWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            plateInputWindow.Show();
        }
        /// <summary>
        /// 将来反填到基础信息的实体
        /// </summary>
        VerifyPlateList verifyPlateList_Temp;
        bool VerifyPlag = false;
        private void DlgDialogEvent_InputPlate_AuthBack(string plateNumber)
        {
            try
            {
                //根据车牌号与日期查找相应的当日可拉的重量信息
                verifyPlateList_Temp = null;
                if (!string.IsNullOrEmpty(plateNumber))
                {
                    tb_InputPlate.Text = plateNumber;
                    BtnInputPlate.Content = "点击修改车牌";

                    //据据车牌号查询数据库当日制卡货物
                    string msg1 = "";
                    string msg2 = "";

                    //请求两次接口
                    //入厂
                    List<VerifyPlateList> listTemp = ServiceWebApi.GetTheSameDayGoodsByPlate(System.DateTime.Now.ToString("yyyy-MM-dd"), "1", plateNumber, out msg1);
                    
                    if (listTemp == null || listTemp.Count() == 0)
                    {
                        //出厂
                        List<VerifyPlateList> listTemp2 = ServiceWebApi.GetTheSameDayGoodsByPlate(System.DateTime.Now.ToString("yyyy-MM-dd"), "2", plateNumber, out msg2);
                        VerifyPlag = false;
                        string str = $"【入厂制卡--验证未通过】此车牌{plateNumber}, 未在当日可制卡信息中, 请联系工作人员";                        
                        //日志加上去
                        SimpleConsole.WriteInfo(str + msg1, null);

                        #region 说明此车牌在出厂制卡信息中 -- 做个提示
                        if (listTemp2 != null && listTemp2.Count() > 0)
                        {
                            // 先判断是不是出厂车辆的车牌
                            this.parent.ShowText($"车牌号:{plateNumber}为出厂车辆，请选择【出厂货物】制卡！");
                            this.parent.PlayVioceQueue.Enqueue($"车牌号:{plateNumber}为出厂车辆，请选择出厂货物制卡！");                            
                            this.parent.Alert("提示", $"车牌号:{plateNumber}为出厂车辆，请选择【出厂货物】制卡！", delegate () {
                                //返回到制卡页面
                                this.parent.Choose_Business(EnterBusinessType.ZKCZ);
                                this.parent.ShowZkczIndex();
                            });
                        }
                        #endregion

                        //因为入厂车辆信息维护不是必须的，所以不加没有维护信息的提示
                        return;//必须跳出去
                    }

                    //需要弹出窗口，选择
                    if (listTemp.Count() > 1)
                    {
                        //弹出页面
                        PlateGoodsListPage view1 = new PlateGoodsListPage(this.parent);
                        view1.Owner = this.parent;
                        view1.ShowInTaskbar = false;
                        view1.InitPage(listTemp);
                        view1.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                        if (view1.ShowDialog() == true)
                        {
                            VerifyPlag = true;
                            verifyPlateList_Temp = view1.ThisRecord;
                            this.parent.ShowText("【验证通过】可提交信息制卡。");
                            this.parent.PlayVioceQueue.Enqueue("验证通过,可提交信息制卡。");
                        }
                        else
                        {
                            VerifyPlag = false;
                            this.parent.PlayVioceQueue.Enqueue("请重新输入车牌,选择本次制卡的货物信息。");
                            this.parent.ShowText("【请重新输入车牌】选择本次制卡的货物信息。");
                            return;
                        }
                    }
                    else
                    {
                        VerifyPlag = true;
                        verifyPlateList_Temp = listTemp[0];
                    }
                    //将信息返填过来
                    ShowThreeInfo(verifyPlateList_Temp);
                }
                else
                {
                    this.parent.ShowText("车牌号不能为空。");
                    this.parent.PlayVioceQueue.Enqueue("车牌号不能为空。");
                    MessageBox.Show("录入车牌号不能为空");
                }
            }
            catch (Exception ex)
            {
                SimpleConsole.WriteInfo("DlgDialogEvent_InputPlate_AuthBack" + ex.ToString(), null);
                this.parent.ShowText("请检与服务器连接是否正常。");
            }
        }
        /// <summary>
        /// 将三大基础信息反显过来
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ShowThreeInfo(VerifyPlateList temp)
        {
            try
            {
                ac_cb_product.Text = temp.GoodsName;
                ac_cb_sender.Text = temp.Sender;
                ac_cb_receiver.Text = temp.Receiver;
                if (temp.PiCi == null)
                {
                    btn_PiCi.Content = "";
                }
                else
                {
                    btn_PiCi.Content = temp.PiCi;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("基础信息显示出错：" + ex.ToString());
            }
        }
        private void BtnInputPlate_Click(object sender, RoutedEventArgs e)
        {
            ShowInputPlateWinDialog();
        }


        public void SetPlate(string Plate)
        {
            if (!string.IsNullOrEmpty(Plate))
            {
                tb_InputPlate.Text = Plate;
            }
        }

        public void SetYNumber(string YNumber)
        {
            if (!string.IsNullOrEmpty(YNumber))
            {
                tb_PutOnRecordNum.Text = YNumber;
            }
        }

        private void BtnInputPutOnRecordNum_MouseUp(object sender, MouseButtonEventArgs e)
        {
            InputPutOnRecordNum();
        }

        private void BtnInputPutOnRecordNum_MouseUp(object sender, RoutedEventArgs e)
        {
            InputPutOnRecordNum();
        }
        private void InputPutOnRecordNum()
        {
            string strYNumber = tb_PutOnRecordNum.Text;
            //显示备案号输入
            this.parent.ShowPutOnRecordInPut(strYNumber);
        }
        #region 数据字键盘
        //当前的输入
        InPutNumberWin view;
        string currentInput = "";
        public string ShowInPutNumberWin(string textInput, string oldNumber)
        {
            //MessageBox.Show("开始输入");
            //提取纯数字，该方式会将所有数字提取出来并拼接在一起，如："ABC#123@AS456测试"提取出来就是123456
            oldNumber = Regex.Replace(oldNumber, @"[^0-9]+", "");
            currentInput = textInput;
            view = null;
            //弹出页面
            view = new InPutNumberWin(currentInput, oldNumber);
            view.Owner = this.parent;
            view.ShowInTaskbar = false;
            view.WindowStartupLocation = WindowStartupLocation.Manual;
            view.Top = 400;
            view.Left = 380;
            if (view.ShowDialog() == true)
            {
                return view.newNumber;
            }
            else
            {
                return oldNumber;
            }
        }

        private void txtSender_Tare_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            //txtSender_Tare.Text = ShowInPutNumberWin("发货皮重", txtSender_Tare.Text.Trim());
        }

        private void tb_Phone_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            //tb_Phone.Text = ShowInPutNumberWin("手机", tb_Phone.Text.Trim());
        }

        private void txtSender_Gross_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            //txtSender_Gross.Text = ShowInPutNumberWin("发货毛重", txtSender_Gross.Text.Trim());
        }

        private void txtSender_Net_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            //txtSender_Net.Text = ShowInPutNumberWin("发货净重", txtSender_Net.Text.Trim());
        }

        private void txtCount_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            //txtCount.Text = ShowInPutNumberWin("件数", txtCount.Text.Trim());
        }
        private void tb_DriverName2_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            //tb_DriverName2.Text = ShowInPutNumberWin("随车人员", tb_DriverName2.Text.Trim());
        }

        private void tb_Phone2_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            //tb_Phone2.Text = ShowInPutNumberWin("人员手机", tb_Phone2.Text.Trim());
        }
        #endregion


        private void ac_cb_product_MouseUp(object sender, RoutedEventArgs e)
        {
            if (ac_cb_product.Text.ToString().Trim() != "")
            {
                switch (ac_cb_product.Text.ToString())
                {
                    case "硫酸92.5%":
                    case "硫酸98%":
                    case "硫酸104.5%":
                        //row50_Number.Visibility = Visibility.Visible;
                        //row51_Number.Visibility = Visibility.Visible;
                        MessageBox.Show("请在选择【出厂货物】页面进行硫酸货物的制卡操作！");
                        return;
                }
            }
            row50_Number.Visibility = Visibility.Hidden;
            row51_Number.Visibility = Visibility.Hidden;
        }

        private void Btn_Product_Click(object sender, RoutedEventArgs e)
        {
            ac_cb_product.Text = "";
        }

        private void Btn_Receiver_Click(object sender, RoutedEventArgs e)
        {
            ac_cb_receiver.Text = "";
        }

        private void Btn_Sender_Click(object sender, RoutedEventArgs e)
        {
            ac_cb_sender.Text = "";
        }
        private void ac_cb_product_MouseUp(object sender, MouseButtonEventArgs e)
        {
            ////LostFocus = "ac_cb_product_LostFocus"
            //if (ac_cb_product.Text.ToString().Trim() != "")
            //{
            //    switch (ac_cb_product.Text.ToString())
            //    {
            //        case "硫酸92.5%":
            //        case "硫酸98%":
            //        case "硫酸104.5%":
            //            //row50_Number.Visibility = Visibility.Visible;
            //            //row51_Number.Visibility = Visibility.Visible;
            //            MessageBox.Show("请在选择【出厂货物】页面进行硫酸货物的制卡操作！");
            //            return;
            //    }
            //}
            //row50_Number.Visibility = Visibility.Hidden;
            //row51_Number.Visibility = Visibility.Hidden;
        }

        private void ac_cb_product_LostFocus(object sender, RoutedEventArgs e)
        {
            if (ac_cb_product.Text.ToString().Trim() != "")
            {
                switch (ac_cb_product.Text.ToString())
                {
                    case "硫酸92.5%":
                    case "硫酸98%":
                    case "硫酸104.5%":
                        //row50_Number.Visibility = Visibility.Visible;
                        //row51_Number.Visibility = Visibility.Visible;
                        MessageBox.Show("请在选择【出厂货物】页面进行硫酸货物的制卡操作！");
                        ac_cb_product.Text = "";
                        return;
                }
            }
            row50_Number.Visibility = Visibility.Hidden;
            row51_Number.Visibility = Visibility.Hidden;
        }

        private void tb_Phone2_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {

        }

        private void tb_Phone2_PreviewMouseDown(object sender, KeyboardFocusChangedEventArgs e)
        {
            //tb_Phone2.Text = ShowInPutNumberWin("人员手机", tb_Phone2.Text.Trim());
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //tb_Phone2.Text = ShowInPutNumberWin("人员手机", tb_Phone2.Text.Trim());
        }

        private void BtnInputNumber_Click(object sender, RoutedEventArgs e)
        {
            Button btn = (Button)sender;
            string key = btn.Name.ToString();
            string tip = "";
            switch (btn.Name.ToString())
            {
                case "btn_Phone":
                    tip = "手机";
                    this.parent.ShowText("");
                    break;
                case "btn_Sender_Tare":
                    tip = "发货皮重";
                    break;
                case "btn_Sender_Gross":
                    tip = "发货毛重";
                    break;
                case "btn_Sender_Net":
                    tip = "发货净重";
                    break;
                case "btn_Count":
                    tip = "件数";
                    break;
                case "btn_Phone2":
                    tip = "人员手机";
                    break;
                case "btn_PiCi":
                    tip = "批次";
                    break;
                default:
                    MessageBox.Show("出错");
                    return;
            }
            btn.Content = ShowInPutNumberWin(tip, btn.Content.ToString());
        }

        private void btn1_Click_1(object sender, RoutedEventArgs e)
        {

        }
    }
}